// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables
import 'dart:async';
import "dart:math";

import 'package:flutter/material.dart';

import 'package:junyeyishu/widgets/QGWebViewWidget.dart';
import 'package:junyeyishu/widgets/QGWidget.dart';
import 'package:junyeyishu/widgets/QGButton.dart';
import 'package:junyeyishu/utils/utils.dart';
import 'package:junyeyishu/widgets/QGNavigationBar.dart';

class QGDisplaceDetail extends StatefulWidget {
  String id;
  QGDisplaceDetail({super.key, required this.id});
  @override
  State<QGDisplaceDetail> createState() => _QGDisplaceDetailState();
}

class _QGDisplaceDetailState extends State<QGDisplaceDetail> {
  dynamic data;

  String? countdown;
  Timer? timer;

  bool canReplacement = false;

  @override
  void dispose() {
    timer?.cancel();
    super.dispose();
  }
 
  @override
  void initState() {
    super.initState();
    onRefresh();
  }

  setupCountdown() {
    var endTime =
        DateTime.parse(data?["end_time"] ?? "").millisecondsSinceEpoch;
    var now = getCurrentTime();

    countdown = getCountdown(data?["start_time"]);
    if (countdown != null || now < endTime) {
      timer?.cancel();
      timer = Timer.periodic(const Duration(seconds: 1), (timer) {
        var now = getCurrentTime();

        //开始时间 & 结束时间
        try {
          var startTime =
              DateTime.parse(data?["start_time"] ?? "").millisecondsSinceEpoch;
          var endTime =
              DateTime.parse(data?["end_time"] ?? "").millisecondsSinceEpoch;
          canReplacement = (now >= startTime) && (now < endTime);
        } catch (e) {}

        countdown = getCountdown(data?["start_time"]);
        if (countdown == null && now > endTime) {
          timer.cancel();
        }
        if (mounted) setState(() {});
      });
    }
  }

  onRefresh() {
    var param = {"event_id": widget.id};
    Map<String, dynamic> stringMap = param.cast<String, dynamic>();

    Network.post(url_user_disassembleEventInfo, data: stringMap).then((res) {
      if (!res.success) {
        toast(res.msg);
        return;
      }

      updateCurrentTime(res.data["timestamp"]);

      data = res.data;

      setupCountdown();
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Stack(
          children: [
            buildContent(),
            buildTop(),
            data == null
                ? Container()
                : Positioned(bottom: 0, child: buildBottom()),
          ],
        ));
  }

  buildContent() {
    if (data == null) {
      return const Center(
          child: CircularProgressIndicator(color: Colors.white));
    }

    return SingleChildScrollView(
      child: Stack(
        children: [
          Column(
            children: [
              SizedBox(height: 70.rpx),
              buildHeader(),
              SizedBox(height: 30.rpx),
              buildCondition(),
              // buildNotice(),
              SizedBox(height: kSafeBottom + 64.rpx),
            ],
          ),
        ],
      ),
    );
  }

  buildTop() {
    return Container(
      color: Colors.transparent,
      child: QGNavigationBar(
        title: data?["event_name"] ?? "藏品分解",
        rightItem: GestureDetector(
          onTap: onRecord,
          child: Container(
            padding: EdgeInsets.only(
                top: 6.rpx, bottom: 6.rpx, left: 10.rpx, right: 10.rpx),
            child: Text(
              '分解记录',
              style: TextStyle(
                  color: Color(0xFF111111),
                  fontSize: 11.rpx,
                  fontWeight: FontWeight.normal),
            ),
          ),
        ),
      ),
    );
  }

  buildHeader() {
    return Container(
      width: kScreenWidth,
      padding: EdgeInsets.symmetric(horizontal: 10.rpx),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Stack(
            alignment: Alignment.center,
            children: [
             
              ClipRRect(
                borderRadius: BorderRadius.circular(8.rpx),
                  child: AspectRatio(
                    aspectRatio:1,
                    child:QGImage(url:data?["thumb_img"]),
                  ),
                ),
                Positioned(
                bottom: 20.rpx,
                right: 40.rpx,
                left: 40.rpx,
                child: 
                countdown != null
              ? Container(
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(26.rpx),
                      color: Color(0x80000000)),
                  padding:
                      EdgeInsets.symmetric(horizontal: 40.rpx, vertical: 6.rpx),
                  child: RichText(
                      textAlign: TextAlign.center,
                      text: TextSpan(children: [
                        buildText('距离开始时间：', Color(0xFFFFFFFF)),
                        buildText('$countdown', Color(0xFFFFFFFF)),
                      ])),
                )
                : Container(),
              )
            ],
          ),
        ],
      ),
    );
  }

  buildText(text, color) {
    return TextSpan(
      text: text,
      style: TextStyle(
          color: color, fontSize: 11.rpx, fontWeight: FontWeight.normal),
    );
  }

  buildCondition() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 10.rpx),
      child: Column(
        children: [
          buildConditionTitle(),
          SizedBox(height: 20.rpx),
          // buildArrow(),
          // SizedBox(height: 14.rpx),
          buildConditionItems(),
          // buildTip(),
        ],
      ),
    );
  }

  buildConditionTitle() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 30.rpx),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          SizedBox(width: 7.rpx),
          Expanded(
            child: Column(
              children: [
                Text(
                  data?["goods_name"] ?? "",
                  style: TextStyle(
                      color: Color(0xFFFFFFFF),
                      fontSize: 20.rpx,
                      fontWeight: FontWeight.bold),
                ),
                // Row(
                //   mainAxisAlignment: MainAxisAlignment.center,
                //   children: [
                //     Text("限量 ",style: TextStyle(fontSize: 13,color: Color(0XFF989EA4))),
                //     Text(data?["event"]?["max_num"] ?? "",style: TextStyle(fontSize: 13,color: Color(0XFF989EA4))),
                //     Text("份 ",style: TextStyle(fontSize: 13,color: Color(0XFF989EA4))),
                //   ]
                // )
              ],
            ),

          ),
          SizedBox(width: 4.rpx),
          
        ],
      ),
    );
  }

  buildArrow() {
    return Align(
      alignment: Alignment.center,
      child: Transform.rotate(
          angle: pi,
          child: QGImage(asset: "synthesis_detail_arrow", width: 29.rpx)),
    );
  }

  buildTip() {
    return Container(
      alignment: Alignment.center,
      child: Text(
        "分解获得以下数字资产",
        style: TextStyle(
            fontWeight: FontWeight.normal,
            fontSize: 12.rpx,
            color: Color(0xFFFFFFFF)),
      ),
    );
  }

  buildConditionItems() {
     List<Widget> children = [];

    for (var item in data?["formula"] ?? []) {
      children.add(buildConditionCell(item));
    }

    return Container(
      padding: EdgeInsets.only(bottom: 10.rpx),
      margin: EdgeInsets.only(bottom: 10.rpx),

      decoration: BoxDecoration(
        color: Color(0XFF232A32)
      ),
      alignment: Alignment.center,
      child:
      Column(
        children: [
          SizedBox(height: 15.rpx,),
          Text("置换条件 ",style: TextStyle(fontSize: 18.rpx,color: Color(0XFFFFFFFF))),
          SizedBox(height: 3.rpx,),
          Text("集齐一下藏品即可兑换",style: TextStyle(fontSize: 13.rpx,color: Color(0XFF989EA4))),
          SizedBox(height: 20.rpx,),

           Wrap(
            spacing: 10.rpx,
            runSpacing: 10.rpx,
            children: children,
          ),
      //       Row(
      //   mainAxisAlignment: MainAxisAlignment.center,
      //   children: [buildConditionCell()],
      // ),
        ],
      ),
     
    );
  }

  buildConditionCell(itemData) {
    // var itemData;
    // if (data?["formula"] is List && data?["formula"].length > 0) {
    //   itemData = data?["formula"][0];
    // }

    return 
    Column(
      children: [
        Container(
            decoration: BoxDecoration(
              color: Color(0XFF0C1012),
              borderRadius: BorderRadius.only(bottomLeft: Radius.circular(5.rpx),bottomRight: Radius.circular(5.rpx),),
            ),
          child: Column(
            children: [
                    QGImage(
                    url: itemData["thumb_img"],
                    width: 155.rpx,
                    height: 155.rpx),
                    SizedBox(height: 10.rpx),
                    Text(
                  itemData["name"] ?? "",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: Color(0xFFffffff),
                      fontSize: 14.rpx,
                      fontWeight: FontWeight.bold),
                ),
                SizedBox(height: 3.rpx),
                    Text(
                        '${itemData["goods_num"]}份',
                        style: TextStyle(
                            color: Color(0xFF989EA4),
                            fontSize: 12.rpx,
                            fontWeight: FontWeight.bold),
                      ),
                      SizedBox(height: 10.rpx),
            ],
          ),
        ),
      ],
    );
    
    // Container(
    //   child: Column(
    //     children: [
    //       Stack(
    //         children: [
    //           Container(
    //             padding: EdgeInsets.only(top: 10.rpx, right: 10.rpx),
    //             child: ClipRRect(
    //               borderRadius: BorderRadius.circular(4.rpx),
    //               child: QGImage(
    //                   url: itemData?["thumb_img"],
    //                   width: 75.rpx,
    //                   height: 75.rpx),
    //             ),
    //           ),
    //           Positioned(
    //             top: 0.rpx,
    //             right: 0.rpx,
    //             child: Container(
    //               alignment: Alignment.center,
    //               padding:
    //                   EdgeInsets.symmetric(horizontal: 8.rpx, vertical: 3.rpx),
    //               decoration: BoxDecoration(
    //                 borderRadius: BorderRadius.circular(10.rpx),
    //                 color: Color(0xFFDEFF80),
    //               ),
    //               child: Text(
    //                 itemData["goods_num"] ?? "",
    //                 style: TextStyle(
    //                     color: Color(0xff111111),
    //                     fontSize: 12.rpx,
    //                     fontWeight: FontWeight.bold),
    //               ),
    //             ),
    //           ),
    //         ],
    //       ),
    //       SizedBox(height: 10.rpx),
    //       Container(
    //         alignment: Alignment.center,
    //         width: 75.rpx,
    //         child: Text(
    //           itemData?["name"] ?? "",
    //           maxLines: 1,
    //           overflow: TextOverflow.ellipsis,
    //           style: TextStyle(
    //               color: Color(0xFF111111),
    //               fontSize: 14.rpx,
    //               fontWeight: FontWeight.bold),
    //         ),
    //       ),
    //       SizedBox(height: 10.rpx),
    //     ],
    //   ),
    // );
  }

  buildNotice() {
    return Container(
      margin: EdgeInsets.only(top: 10.rpx, left: 10.rpx, right: 10.rpx),
      padding: EdgeInsets.all(20.rpx),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10.rpx),
        color: Color(0xFFFFFFFF),
      ),
      child: Column(children: [
        Text(
          '分解须知',
          style: TextStyle(
              color: Color(0xFF111111),
              fontSize: 16.rpx,
              fontWeight: FontWeight.bold),
        ),
        QGWebViewWidget(
            str: data?["event_content"],
            bgColor: "#ffffff",
            textColor: "#111111")
      ]),
    );
  }

  buildBottom() {
    return Container(
      padding: EdgeInsets.only(
          left: 20.rpx,
          right: 20.rpx,
          top: 10.rpx,
          bottom: max(10, kSafeBottom)),
      width: kScreenWidth,
      decoration: BoxDecoration(color: Color(0xFF232A32)),
      child: QGButton(
        title: "立即置换",
        enable: data?["isQualified"] != 0 && canReplacement,
        onTap: onCompose,
      ),
    );
  }

  onRecord() {
    Navigator.of(context).pushNamed(PageDisplaceRecord, arguments: widget.id);
  }
  onCompose() {
    var param = {"event_id": widget.id};
    Map<String, dynamic> stringMap = param.cast<String, dynamic>();

    Network.post(url_user_disassembleNft, data: stringMap, context: context)
        .then((res) {
      if (!res.success) {
        toast(res.msg);
        return;
      }
      toast(res.data["message"] ?? "");
      onRefresh();
    });
  }
}
